package com.project.interceptor;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dtyunxi.rest.RestResponse;
import com.dtyunxi.util.JacksonUtil;
import com.dtyunxi.util.WeiXinApi;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.project.common.Constants;
import com.project.entity.user.User;
import com.project.service.IUserService;
import com.project.util.EhcacheUtil;
import com.project.util.HttpRequest;
import com.project.util.SpringUtil;
import com.project.util.WeiXinUtil;

public class LoginInterceptor implements HandlerInterceptor{
	
	private final static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		logger.info("------------------登录拦截.requestMethod:{}, url:{}------------------",request.getMethod(),request.getRequestURI());
		//只要是带自定义header的跨域请求，在发送真实请求前都会先发送OPTIONS请求，
		//浏览器根据OPTIONS请求返回的结果来决定是否继续发送真实的请求进行跨域资源访问。所以复杂请求肯定会两次请求服务端。
		if("OPTIONS".equals(request.getMethod().toUpperCase())){
			return true;
		}
		String auth = request.getHeader("auth");
		logger.info("------------------登录拦截.auth:{}------------------",auth);
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Constants.CURRENT_LOGIN_USER);
		logger.info("------------------user:{}------------------",user);
		if(user==null){
			if(StringUtils.isNotBlank(auth)){
				User cacheUser = (User) EhcacheUtil.get(Constants.LOGIN_USER_CACHE, auth);
				if(cacheUser!=null){
					logger.info("------------------缓存中有登录用户数据------------------");
					session.setAttribute(Constants.CURRENT_LOGIN_USER, cacheUser);
					return true;
				}else{
					logger.info("------------------缓存中没有数据，返回401------------------");
					writeNoLoginJson(response);
					/*//浏览器类型:微信客户端访问时候user-agent信息如下：
					//Mozilla/5.0 (Linux; Android 5.0.1; M040 Build/LRX22C) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/37.0.0.0 Mobile MQQBrowser/6.8 TBS/036872 Safari/537.36 MicroMessenger/6.3.31.940 NetType/WIFI Language/zh_CN
					//其中MicroMessenger代表是微信客户端访问的，所以只要判断是否含有MicroMessenger即可。
					String userAgent = request.getHeader("user-agent").toLowerCase();
					logger.info("------------------浏览器类型.userAgent:{}------------------", userAgent);
					if(userAgent.indexOf("micromessenger")>-1){//微信客户端获取openid
						logger.info("------------------微信浏览器,获取openid------------------");
						String code = request.getParameter("code");
						if(StringUtils.isBlank(code)){//oauth获取code
							logger.info("===================跳转第一次======================");
							String redirectUrl = HttpRequest.getRequestFullUriNoContextPath(request);//请求code的回调url
							System.out.println(redirectUrl);
							String url = WeiXinApi.getOAuthCodeUrl(Constants.WX_APPID, redirectUrl, "snsapi_base", "");
							HttpRequest.redirectHttpUrl(request,response, url);
							return false;
						}else{
							logger.info("===================跳转第二次======================");
							try {
								String openid = WeiXinUtil.getOpenid(Constants.WX_APPID, Constants.WX_APPSECRET, code);
								if(!StringUtils.isBlank(openid)){
									//通过openid找用户
									IUserService userService = (IUserService) SpringUtil.getBean("userServiceImpl");
									User dbUser = userService.getByOpenid(openid);
									//用户信息放session
									if(dbUser!=null){
										EhcacheUtil.put(Constants.LOGIN_USER_CACHE, auth, dbUser);
										session.setAttribute(Constants.CURRENT_LOGIN_USER, dbUser);
									}else{
										logger.info("------------------微信浏览器,没有登录，返回401------------------");
										writeNoLoginJson(response);
									}
								}
							} catch (Exception e) {
								logger.error(e.getMessage(),e);
							}
						}
					}else{//非微信浏览器
						logger.info("------------------非微信浏览器，返回401------------------");
						writeNoLoginJson(response);
					}*/
				}
			}else{
				logger.info("------------------auth为空,没有登录，返回401------------------");
				writeNoLoginJson(response);
			}
		}else{
			return true;
		}
		return false;
	}
	
	private void writeNoLoginJson(HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		RestResponse restResponse = new RestResponse(401,"no login",null);
		try {
			response.getWriter().write(JacksonUtil.toJson(restResponse));
		} catch (JsonProcessingException e) {
			logger.error(e.getMessage(), e);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}
	
}
